<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue'
import { regionData, CodeToText } from 'element-china-area-data'
import { useRegisterStore } from '@/stores/register'
import { useUserStore } from '@/stores/user'
import { useAccountsetStore } from '@/stores/accountset'
import { useMessage } from 'naive-ui'
import { getToken } from '@/utils/storage'
import bus from '@/utils/index'

onMounted(() => {
	const info = userStore.userInfo
	model.value.name = info?.name
	model.value.loginName = info?.loginName
	model.value.introduction = info?.introduction
	model.value.tel = info?.tel
	model.value.position = info?.position
	model.value.logo = info?.logo
	selectedOptions.value = info?.address
})

const message = useMessage()
const accountsetStore = useAccountsetStore()
const registerStore = useRegisterStore()
const userStore = useUserStore()
const formRef = ref()
const formRef2 = ref()
const options = regionData
const selectedOptions = ref([])

const model = ref({
	name: '',
	loginName: '',
	introduction: '',
	tel: '',
	position: '',
	loginKey: '',
	newLoginKey: '',
	newLoginKey2: '',
	logo: ''
})

const validatePasswordStartWith = function (rule, value) {
	return (
		!!model.value.newLoginKey &&
		model.value.newLoginKey.startsWith(value) &&
		model.value.newLoginKey.length >= value.length
	)
}

const validatePasswordSame = function (rule, value) {
	return value === model.value.newLoginKey
}

const validatePasswordSame2 = function (rule, value) {
	return value !== model.value.loginKey
}


const rules = reactive({
	name: {
		required: true,
		trigger: ['blur'],
		validator: (rule, value) => {
			return new Promise(async (resolve, reject) => {
				const res = await registerStore.checkStatus(value)
				if (res?.data[0]?.name && (res?.data[0]?.name != userStore.userInfo.name)) {
					reject(Error('店铺名称已存在'))
				} else if (!value) {
					reject(Error('请输入店铺名称'))
				} else {
					resolve(true)
				}
			})
		}
	},
	loginKey: {
		required: true,
		trigger: ['blur'],
		message: '请输入旧密码'
	},
	newLoginKey: [
		{
			required: true,
			trigger: ['blur'],
			message: '请输入新密码'
		},
		{
			validator: validatePasswordSame2,
			message: '新密码不能和旧密码相同',
			trigger: ['blur', 'password-input']
		}
	],
	newLoginKey2: [
		{
			required: true,
			message: '请再次输入新密码',
			trigger: ['blur']
		},
		{
			validator: validatePasswordStartWith,
			message: '两次密码输入不一致',
			trigger: 'input'
		},
		{
			validator: validatePasswordSame,
			message: '两次密码输入不一致',
			trigger: ['blur', 'password-input']
		}
	],
	introduction: {
		required: true,
		trigger: ['blur'],
		message: '请输入店铺介绍'
	},
	tel: {
		required: true,
		trigger: ['blur'],
		message: '请输入联系电话',
	},
	position: {
		required: true,
		trigger: ['blur'],
		message: '请输入详细地址'
	}
})

const saveAccount = () => {
	formRef.value?.validate(async (errors) => {
		if (!errors) {
			bus.emit('imgChange', model.value)
			console.log('验证通过')
			await accountsetStore.doModify(model.value, selectedOptions.value, userStore.userInfo)
			userStore.getUserInfo(getToken())
			message.success('修改成功')
		} else {
			console.log(errors)
		}
	})
}

const saveNewKey = () => {
	formRef2.value?.validate(async (errors) => {
		if (!errors) {
			console.log('验证通过')
			if (model.value.loginKey === userStore.userInfo.loginKey) {
				await accountsetStore.modifyKey(model.value.newLoginKey, userStore.userInfo)
				userStore.getUserInfo(getToken())
				message.success('修改成功')
			} else {
				message.error('旧密码输入错误')
			}
			model.value = {
				loginKey: '',
				newLoginKey: '',
				newLoginKey2: '',
			}
		} else {
			console.log(errors)
		}
	})
}

const onFinishUpload = (file) => {
	const logo = JSON.parse(file.event.currentTarget.response).data
	model.value.logo = logo
}

const onRemoveLogo = () => {
	model.value.logo = userStore.userInfo.logo
}


</script>

<template>

	<n-card>
		<n-tabs class="card-tabs" default-value="signin" size="large" animated style="margin: 0 -4px"
			pane-style="padding-left: 4px; padding-right: 4px; box-sizing: border-box;">
			<n-tab-pane name="signin" tab="账号设置">
				<n-form ref="formRef" :model="model" :rules="rules" label-placement="left" label-width="auto"
					require-mark-placement="left" :style="{ width: '60%' }">
					<n-form-item label="LOGO:" path="inputValue">
						<div class="wap">
							<n-upload action="http://localhost:3009/user/upload" name="icon" :max="1"
								:show-file-list="true" :on-finish="onFinishUpload" :on-remove="onRemoveLogo">
								<n-button type="primary" style="width: 130px;" dashed>上传LOGO</n-button>
							</n-upload>
							<n-avatar style="width: 130px;height: 130px;margin-top: 20px;" :size="48" v-if="model.logo"
								:src="`http://localhost:3009/upload/${model.logo}`" />
							<n-avatar style="width: 130px;height: 130px;margin-top: 20px;" :size="48" v-else
								src="http://img.duoziwang.com/2020/03/09231400594857.jpg" />
						</div>
					</n-form-item>
					<n-form-item label="店铺名称:" path="name">
						<n-input v-model:value="model.name" placeholder="请输入店铺名称" />
					</n-form-item>
					<n-form-item label="店铺介绍:" path="introduction">
						<n-input v-model:value="model.introduction" placeholder="请输入店铺介绍" type="textarea"
							:autosize="{ minRows: 3, maxRows: 5 }" />
					</n-form-item>
					<n-form-item label="联系电话:" path="tel">
						<n-input v-model:value="model.tel" placeholder="请输入联系电话" />
					</n-form-item>

					<n-form-item label="店铺地址:" path="selectedOptions">
						<el-cascader size='large' placeholder="请选择地址" :options='options' v-model='selectedOptions'>
						</el-cascader>
					</n-form-item>

					<n-form-item label="详细地址:" path="position">
						<n-input v-model:value="model.position" placeholder="请输入详细地址" type="textarea"
							:autosize="{ minRows: 3, maxRows: 5 }" />
					</n-form-item>
				</n-form>
				<n-button type="primary" @click="saveAccount" style="width: 27%; margin-top: 30px; margin-left: 173px;">
					保存
				</n-button>
			</n-tab-pane>
			<n-tab-pane name="signup" tab="修改密码">
				<n-form ref="formRef2" :model="model" :rules="rules" label-placement="left" label-width="auto"
					require-mark-placement="right-hanging" :style="{ width: '60%' }">
					<n-form-item label="旧密码:" path="loginKey">
						<n-input v-model:value="model.loginKey" type="password" placeholder="请输入旧密码" />
					</n-form-item>
					<n-form-item label="新密码:" path="newLoginKey">
						<n-input v-model:value="model.newLoginKey" type="password" placeholder="请输入新密码" />
					</n-form-item>
					<n-form-item label="确认新密码:" path="newLoginKey2">
						<n-input v-model:value="model.newLoginKey2" type="password" placeholder="请确认新密码" />
					</n-form-item>
				</n-form>
				<n-button type="primary" @click="saveNewKey" style="width:27%; margin-top:30px; margin-left:173px;">
					保存
				</n-button>
			</n-tab-pane>
		</n-tabs>
	</n-card>
</template>

<style scoped>
.wap {
	display: flex;
	flex-direction: column;
}
</style>